package com.wy;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.json.JSONObject;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

@RestController
@RequestMapping("/location")
public class LocationController {
    @Value("${location.api.url}")
    private String apiUrl;

    @GetMapping("/info")
    public String getLocationInfo(HttpServletRequest request) {
        String ipAddress = request.getRemoteAddr();
        ipAddress = "114.246.236.19";
        String locationInfo = getLocationByIp(ipAddress);
        return locationInfo != null ? locationInfo : "无法获取位置信息";
    }

    private String getLocationByIp(String ip) {
        try {
            String fullApiUrl = apiUrl + ip;
            System.out.println("请求的 API URL: " + fullApiUrl); // 打印请求的 URL
            HttpURLConnection connection = (HttpURLConnection) new URL(fullApiUrl).openConnection();
            connection.setRequestMethod("GET");
            connection.setRequestProperty("User-Agent", "Mozilla/5.0"); // 添加 User-Agent

            int responseCode = connection.getResponseCode();
            System.out.println("响应状态码: " + responseCode); // 打印响应状态码

            if (responseCode == HttpURLConnection.HTTP_OK) {
                BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                StringBuilder response = new StringBuilder();
                String inputLine;
                while ((inputLine = in.readLine()) != null) {
                    response.append(inputLine);
                }
                in.close();

                // 解析 JSON 响应
                JSONObject jsonResponse = new JSONObject(response.toString());
                if (jsonResponse.getString("status").equals("success")) {
                    String province = jsonResponse.getString("regionName");
                    String city = jsonResponse.getString("city");
                    String street = jsonResponse.optString("street", "未知街道");
                    return String.format("请求位置: 省: %s, 市: %s, 街道: %s", province, city, street);
                } else {
                    return "无法获取位置信息: " + jsonResponse.getString("message");
                }
            } else {
                return "无法获取位置信息: 响应状态码 " + responseCode;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return "发生错误: " + e.getMessage();
        }
    }
} 